﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Depts;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Depts
{
    public class SelectDeptMenuCommandHandler : IRequestHandler<SelectDeptMenuCommand, APIResult<List<DeptMenuItem>>>
    {
        IBaseRepository<Dept> dRep;
        ILogger<SelectDeptMenuCommandHandler> logger;

        public SelectDeptMenuCommandHandler(IBaseRepository<Dept> dRep, ILogger<SelectDeptMenuCommandHandler> logger)
        {
            this.dRep = dRep;
            this.logger = logger;
        }

        public async Task<APIResult<List<DeptMenuItem>>> Handle(SelectDeptMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await GetDeptList(0);
                return new APIResult<List<DeptMenuItem>>
                {
                    Code=StatusEnumCode.Ok,
                    Message="返回部门列表成功",
                    Data=list
                };
            }
            catch (Exception ex)
            {
                logger.LogError("返回部门列表出错！" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 递归获取指定父部门下的所有子部门，构建树形结构的部门菜单数据
        /// </summary>
        /// <param name="parentId">父级ID</param>
        /// <returns></returns>
        public async Task<List<DeptMenuItem>> GetDeptList(int parentId)
        {
            try
            {
                //从数据库中查询当前父部门ID下的所有直接子部门
                var list =await dRep.GetAll().Where(x=>x.ParentId == parentId).ToListAsync();
                //初始化用于存储树形结构的部门菜单项列表
                var deptlist =new List<DeptMenuItem>();
                // 遍历查询到的每个子部门，构建树形结构
                foreach (var item in list)
                {
                    // 将数据库实体转换为菜单项，并递归获取当前部门的所有子部门
                    deptlist.Add(new DeptMenuItem
                    {
                        value = item.DeptId,          // 设置菜单项的值为部门ID
                        label = item.DeptName,        // 设置菜单项的显示文本为部门名称
                        children = await GetDeptList(item.DeptId), // 递归获取当前部门的子部门列表
                    });
                }
                // 返回构建好的树形结构部门菜单
                return deptlist;
            }
            catch (Exception ex)
            {
                logger.LogError("返回部门列表出错！" + ex.Message);
                throw;
            }
        }
    }
}
